package com.fenfen.novel.rest;

import android.content.Context;
import android.support.annotation.NonNull;

import com.fenfen.novel.utils.CommonUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class CachingControlInterceptor implements Interceptor {
  private static String Tag = CachingControlInterceptor.class.getSimpleName();
  private Context mContext;
  private static int netMaxAge = 60 * 60 * 2; //有网络，缓存2小时
  private static int unNetMaxAge = 60 * 60 * 24 * 28; //无网络，缓存4周

  public CachingControlInterceptor(Context context) {
    this.mContext = context;
  }

  @Override
  public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();
    // Add Cache Control only for GET methods
    if (originalRequest.method().equals("GET")) {
      Request modifyRequest = originalRequest.newBuilder().header("Cache-Control", cacheControl()).build();

      return chain.proceed(modifyRequest);
    }
    return chain.proceed(originalRequest);
  }

  @NonNull
  private String cacheControl() {
    String cacheControl;
    if (CommonUtil.isNetworkReachable(mContext)) {
      cacheControl = "public, max-age=" + netMaxAge;
    } else {
//      cacheControl = CacheControl.FORCE_CACHE.toString();
      cacheControl = "public, max-age=" + unNetMaxAge;
    }
    return cacheControl;
  }

}